import axios, { CancelTokenSource } from 'axios';

export class CancelHolder {
  static isCancel = (err: any) => axios.isCancel(err);

  private _source: CancelTokenSource | undefined;

  private cancelToken() {
    this._source = this._source || axios.CancelToken.source();
    return this._source.token;
  }

  private _controller: AbortController | undefined;
  private signal() {
    this._controller = this._controller || new window.AbortController;
    return this._controller.signal;
  }
  cancelled() {
    if (window.AbortController)
      return this.signal().aborted;
    else
      return this.cancelToken().reason !== void 0;
  }
  signals() {
    if (window.AbortController)
      return { signal: this.signal() };
    else
      return { cancelToken: this.cancelToken() };
  }

  cancel = (reason?: any) => {
    this._source?.cancel(reason);
    this._controller?.abort(reason);
    delete this._source;
    delete this._controller;
  };

  static ignoreCancelErr = (e: any) => {
    if (!axios.isCancel(e))
      throw e;
  };

  ignoreCancelErr = CancelHolder.ignoreCancelErr
  ignore = CancelHolder.ignoreCancelErr
}
